/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年11月3日         Root.Lu
 */

package com.coocaa.x.service.litedownloader;

import android.content.Context;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.app.CoocaaService.AIDLInterface;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedownloader.aidl.IDownloaderService.Stub;
import com.coocaa.x.service.litedownloader.aidl.IDownloaderServiceListener;
import com.coocaa.x.service.litedownloader.data.DownloadError;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.ProcessInfo;
import com.coocaa.x.service.litedownloader.db.DownloaderDB;
import com.coocaa.x.service.litedownloader.downloader.Downloader.DownloaderListener;
import com.coocaa.x.service.litedownloader.downloader.DownloaderManager;
import com.coocaa.x.service.litepm.data.InstallParams;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class DownloaderStub extends Stub implements DownloaderListener {
    private Vector<AIDLInterface<IDownloaderServiceListener>> remoteDownloaderListener = new Vector<AIDLInterface<IDownloaderServiceListener>>();

    private DownloaderManager dmanager = null;
    private Context mContext = null;

    public DownloaderStub(Context c) {
        mContext = c;
        DownloaderDB.create(c);
        dmanager = DownloaderManager.getInstance();
        dmanager.setListener(this);
    }


    @Override
    public void whoAmI() {
        LogUtils.d("wai", "<<LiteDownloaderService>> who am i??  " + mContext.getPackageName());
    }

    @Override
    public int add(DownloadTask task) throws RemoteException {
        // TODO Auto-generated method stub
        int ret = dmanager.add(task);
        return ret;
    }

    @Override
    public synchronized int start(DownloadTask task) throws RemoteException {
        // TODO Auto-generated method stub
        int ret = dmanager.start(task);
        return ret;
    }

    @Override
    public synchronized int stop(DownloadTask task) throws RemoteException {
        // TODO Auto-generated method stub
        int ret = dmanager.stop(task);
        return ret;
    }

    @Override
    public synchronized int delete(DownloadTask task) throws RemoteException {
        // TODO Auto-generated method stub
        int ret = dmanager.delete(task);
        return ret;
    }

    @Override
    public synchronized int toFirst(DownloadTask task) throws RemoteException {
        // TODO Auto-generated method stub
        int ret = dmanager.toFirst(task);
        return ret;
    }

    @Override
    public synchronized int startAll() throws RemoteException {
        // TODO Auto-generated method stub
        int ret = dmanager.startAll();
        return ret;
    }

    @Override
    public synchronized int stopAll() throws RemoteException {
        // TODO Auto-generated method stub
        int ret = dmanager.stopAll();
        return ret;
    }

    @Override
    public List<DownloadTask> getTaskListByState(String task_state) throws RemoteException {
        // TODO Auto-generated method stub
        List<DownloadTask> ret = new ArrayList<DownloadTask>();
        List<DownloadTask> tasks = dmanager.getTaskList();
        for (DownloadTask task : tasks) {
            if (task.info.state.toString().equals(task_state))
                ret.add(task);
        }
        return ret;
    }

    @Override
    public synchronized DownloadTask refresh(DownloadTask task) throws RemoteException {
        // TODO Auto-generated method stub
        return dmanager.refresh(task);
    }

    @Override
    public synchronized List<DownloadTask> getTaskList() throws RemoteException {
        // TODO Auto-generated method stub
        return dmanager.getTaskList();
    }

    @Override
    public synchronized void setListener(IDownloaderServiceListener listener)
            throws RemoteException {
        // TODO Auto-generated method stub
        synchronized (remoteDownloaderListener) {
            LogUtils.d("setProviderListener:" + listener);
            if (listener != null) {
                IBinder binder = listener.asBinder();
                LogUtils.d("setProviderListener IBinder:" + binder);
                AIDLInterface<IDownloaderServiceListener> i = new AIDLInterface<IDownloaderServiceListener>(
                        binder, listener);
                remoteDownloaderListener.add(i);
            }
        }
    }

    @Override
    public synchronized void clearListener(IDownloaderServiceListener listener)
            throws RemoteException {
        // TODO Auto-generated method stub
        synchronized (remoteDownloaderListener) {
            LogUtils.d("clearProviderListener:" + listener);
            if (listener != null) {
                IBinder binder = listener.asBinder();
                LogUtils.d("clearProviderListener IBinder:" + binder);
                for (AIDLInterface<IDownloaderServiceListener> i : remoteDownloaderListener) {
                    if (i.binder == binder) {
                        remoteDownloaderListener.remove(i);
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onReady(final DownloadTask task) {
        // TODO Auto-generated method stub
        LogUtils.i(DownloaderService.TAG, "DownloaderService onReady task:" + task.ID + "/" + task.title);
        synchronized (remoteDownloaderListener) {
            for (final AIDLInterface<IDownloaderServiceListener> i : remoteDownloaderListener) {
                AsyncTask.runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            i.i.onReady(refresh(task));
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onPrepare(final DownloadTask task) {
        // TODO Auto-generated method stub
        LogUtils.i(DownloaderService.TAG, "DownloaderService onPrepare task:" + task.ID + "/"
                + task.title);
        synchronized (remoteDownloaderListener) {
            for (final AIDLInterface<IDownloaderServiceListener> i : remoteDownloaderListener) {
                AsyncTask.runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            i.i.onPrepare(refresh(task));
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onStart(final DownloadTask task) {
        // TODO Auto-generated method stub
        LogUtils.i(DownloaderService.TAG, "DownloaderService onStart task:" + task.ID + "/" + task.title);
        synchronized (remoteDownloaderListener) {
            for (final AIDLInterface<IDownloaderServiceListener> i : remoteDownloaderListener) {
                AsyncTask.runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            i.i.onStart(refresh(task));
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onStop(final DownloadTask task) {
        // TODO Auto-generated method stub
        LogUtils.i(DownloaderService.TAG, "DownloaderService onStop task:" + task.ID + "/" + task.title);
        synchronized (remoteDownloaderListener) {
            for (final AIDLInterface<IDownloaderServiceListener> i : remoteDownloaderListener) {
                AsyncTask.runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            i.i.onStop(refresh(task));
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onFinish(final DownloadTask task) {
        // TODO Auto-generated method stub
        LogUtils.i(DownloaderService.TAG, "DownloaderService onFinish task:" + task.ID + "/"
                + task.title);

        DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
        // BigDataLog.log4DownloadSuccess(extra.title, extra.pkgname);
        synchronized (remoteDownloaderListener) {
            for (final AIDLInterface<IDownloaderServiceListener> i : remoteDownloaderListener) {
                AsyncTask.runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            i.i.onFinish(refresh(task));
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
        String installing_apk = task.savepath + task.filename;
        LogUtils.d("installing_apk:" + installing_apk);
        try {
            InstallParams params = new InstallParams();
            params.setFrom(InstallParams.INSTALL_FROM.COOCAA_MARKET);
            XServiceManager.getLitePMService().install(installing_apk, CoocaaApplication.isRoot(), params);
        } catch (RemoteException e) {
        }
    }

    @Override
    public void onDelete(final DownloadTask task) {
        // TODO Auto-generated method stub
        LogUtils.i(DownloaderService.TAG, "DownloaderService onDelete task:" + task.ID + "/"
                + task.title);
        synchronized (remoteDownloaderListener) {
            for (final AIDLInterface<IDownloaderServiceListener> i : remoteDownloaderListener) {
                AsyncTask.runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            i.i.onDelete(refresh(task));
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onProcessInfo(final DownloadTask task, final ProcessInfo info) {
        // TODO Auto-generated method stub
        synchronized (remoteDownloaderListener) {
            for (final AIDLInterface<IDownloaderServiceListener> i : remoteDownloaderListener) {
                AsyncTask.runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            i.i.onProcessInfo(refresh(task), info);
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onError(final DownloadTask task, final DownloadError error) {
        // TODO Auto-generated method stub
        LogUtils.i(DownloaderService.TAG, "DownloaderService onError task:" + task.ID + "/" + task.title);

        DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
        //BigDataLog.log4DownloadError(task.url, extra.title, extra.pkgname, error.error);

        if (error.errcode == DownloadError.ERRCODE_MD5_CHECK_ERROR) {
            try {
                delete(task);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        synchronized (remoteDownloaderListener) {
            for (final AIDLInterface<IDownloaderServiceListener> i : remoteDownloaderListener) {
                AsyncTask.runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            i.i.onError(refresh(task), error);
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    @Override
    public boolean hasTask(String id) throws RemoteException {
        return dmanager.hasTask(id);
    }

    @Override
    public DownloadTask getTask(String id) throws RemoteException {
        return dmanager.getTask(id);
    }

    @Override
    public String getDownloadPath() throws RemoteException {
        // TODO 记得修改这个接口
        return "";
        // return AppDataProvider.getInstance().getDownloadPath();
    }
}
